package com.apes.fn.scm.retailOrder.service.account.retail;

import com.alibaba.fastjson.JSONObject;
import com.apes.crm.business.model.InsuranceCompanyDetail;
import com.apes.fn.business.fixedLoss.service.FixedLossToForeign;
import com.apes.fn.scm.insuranceRules.InsuranceRule;
import com.apes.fn.scm.insuranceRules.InsuranceRuleService;
import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.model.RetailOrderItem;
import com.apes.fn.scm.retailOrder.service.account.RetailAccountData;
import com.apes.fn.scm.retailOrder.service.account.BackBatchAndSupplierService;
import com.apes.fn.scm.retailOrder.service.expense.InsuranceDiscount;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.fn.server.servicePlan.repository.ServicePlanItemRepository;
import com.apes.framework.api.SpringManager;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.account.model.AccountingMethod;
import com.apes.scm.account.account.model.InventoryMode;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.service.TaxService;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.contract.service.ContractService;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.model.VoucherItem;
import com.apes.scm.voucher.service.BusinessType;
import com.apes.scm.voucher.service.VoucherType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 同公司委托定损销售账目
 *
 * @Author wuq
 * @Date 2021-9-22
 */
@RetailAccount(value = "insuranceDiscount", name = "同公司委托定损销售")
@Service
public class InsuranceDiscountVoucherService extends BackBatchAndSupplierService {

    @Autowired
    private ContractService contractService;
    @Autowired
    private TaxService taxService;

    public void process(RetailAccountData retailAccountData) {
        RetailOrder retailOrder = retailAccountData.getRetailOrder();

        InsuranceRule insuranceRule = SpringManager.getBean(InsuranceRuleService.class)
                .findByDeptAndInsuranceCompany(retailOrder.getServiceDept(), retailOrder.getInsuranceCompany());
        if (Objects.isNull(insuranceRule)) throw new RuntimeException("没有找到对应的车型规则,，部门："+ retailOrder.getServiceDept().getId() + "，保险公司："+ retailOrder.getInsuranceCompany().getId());
        if (!retailOrder.getServiceDept().getCompany().getId().equals(insuranceRule.getCompany().getId())) throw new RuntimeException("同公司委托定损基地不能对保险公司开票！");

        /** 直接生成对保险公司的分销单 **/
        createInsuranceSale(retailOrder);

        // 创建费用单
        InsuranceDiscount insuranceDiscount = new InsuranceDiscount(retailOrder);
        insuranceDiscount.create(new JSONObject());
    }

    private void createInsuranceSale(RetailOrder retailOrder) {
        Voucher voucher = getDefaultVoucher(retailOrder, BusinessType.SALE_ORDER);
        voucher.setInventoryMode(InventoryMode.IM_OWN);     //设置库存模式：自有
        voucher.setAccountingMethod(AccountingMethod.AM_PURCHASE);  // 核算方式：经销
        voucher.setCustomerExpand(retailOrder.getCustomerExpand().getId());
        voucher.setClassification(VoucherType.ENTRUST_LOSS);    // 委托定损

        // 通过保险公司明细找保险公司客户
        InsuranceCompanyDetail companyDetail = SpringManager.getBean(FixedLossToForeign.class)
                .getInsuranceCompanyToClient(retailOrder.getInsuranceCompany(), retailOrder.getServiceDept());
        voucher.setPartner( companyDetail.getClient() );

        Contract contract = contractService.getContract(retailOrder.getDept(), voucher.getPartner(), "distribution", "customer", "同公司委托定损销售业务");
        voucher.setContract(contract);

        voucher.setVoucherItems(
                retailOrder.getSaleItems().stream().map(
                        retailOrderItem -> {
                            VoucherItem voucherItem = getDefaultVoucherItem(retailOrderItem);
                            voucherItem.setOwner(retailOrder.getCompany());

                            Tax tax = taxService.getSaleTax(retailOrder.getCompany(), retailOrderItem.getProduct());
                            voucherItem.setTax(tax);

                            // 计算比例对应的单价以及金额
                            voucherItem.setPriceUnit( retailOrderItem.getPriceUnit() );

                            // 检查是否为工单的内协的
                            if (retailOrderItem.getProductRule() == 20) {
                                ServicePlanItem servicePlanItem = SpringManager.getBean(ServicePlanItemRepository.class).findById(retailOrderItem.getOriginnumber()).orElse(null);
                                if (servicePlanItem != null) {
                                    voucherItem.setSupplier(servicePlanItem.getSupplier());
                                    voucherItem.setInventoryBatch(servicePlanItem.getInventoryBatch());
                                }
                            }
                            return voucherItem;
                        }).collect(Collectors.toSet())
        );
        Voucher saleVoucher = invoke("voucher.create", MapUtil.mapped(voucher));

        //增加账单
        createInvoiceAndFixOriginNumber(retailOrder, saleVoucher);
    }

    private Voucher getDefaultVoucher(RetailOrder retailOrder, String businessType) {
        Voucher voucher = new Voucher();
        voucher.setDept(retailOrder.getDept());
        voucher.setCompany(retailOrder.getCompany());
        voucher.setPartner(retailOrder.getCompany().getParty().getPatyRoleByType("Customer"));
        voucher.setBusinessType(businessType);
        voucher.setClerk(retailOrder.getClerk()); //业务员
        voucher.setScene(retailOrder.getScene());
        voucher.setOrigin(retailOrder.getId());
        voucher.setOriginBusinessType(retailOrder.getInnerBusinessType());
        voucher.setSource(retailOrder.getId());
        voucher.setSourceBusinessType(retailOrder.getInnerBusinessType());
        return voucher;
    }

    private VoucherItem getDefaultVoucherItem(RetailOrderItem item) {
        VoucherItem voucherItem = new VoucherItem();
        voucherItem.setProduct(item.getProduct());
        voucherItem.setTax(item.getTax());
        voucherItem.setOwner(item.getOwner());
        voucherItem.setUom(item.getUom());          // 设置为销售的单位以及数量
        voucherItem.setProductQty(item.getProductUomQty());
        voucherItem.setPriceUnit(item.getPriceUnit());      // 默认为零售单价
        voucherItem.setInventoryBatch(item.getInventoryBatch());    // 指定销售批次
        voucherItem.setOriginItemId(item.getId());
        voucherItem.setSourceItemId(item.getId());
        voucherItem.setSupplier(item.getSupplier());
        voucherItem.setDiscount(item.getDiscountAmount());
        return voucherItem;
    }

}
